package edu.tjpu.share.newui;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;

import org.androidpn.client.Constants;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView.BufferType;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.po.Server;
import edu.tjpu.share.po.UserVo;
import edu.tjpu.share.task.LoginTask;
import edu.tjpu.share.util.FileUtil;

public class Login extends Activity {
	private EditText txt_username;
	private EditText txt_pwd;
	private Button btn_login;
	private Server serverinfo;
	private static UserVo userBack;
	private UserVo user;
	ProgressDialog progressDialog;
	private SharedPreferences share;
	private boolean needavatar;
	private byte[] avatarBytes;

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();

		serverinfo = (Server) bundle.getSerializable(Fields.SERVER_INFO);

		user = new UserVo();
		userBack = null;

		setContentView(R.layout.login);

		txt_username = (EditText) findViewById(R.id.login_username);
		txt_pwd = (EditText) findViewById(R.id.login_password);
		btn_login = (Button) findViewById(R.id.login_button);

		btn_login.setOnClickListener(new LoginListener());
		// xmpp
		SharedPreferences sharedPrefsxmpp = getSharedPreferences(
				Constants.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		user.setXmppUsername(sharedPrefsxmpp.getString(Constants.XMPP_USERNAME,
				""));
		// xmpp
		share = Login.this.getSharedPreferences("perference", MODE_PRIVATE);

		String unamestr;
		String upasswdstr;

		unamestr = share.getString(Fields.USER_NAME, "");
		upasswdstr = share.getString(Fields.USER_PASSWD, "");

		// 头像处理
		java.io.File cache = Login.this.getCacheDir();
		java.io.File cacheFile = new java.io.File(cache, Fields.USER_AVATAR);
		if (cacheFile.exists()) {

			try {
				avatarBytes = FileUtil.readFileInBytes(cacheFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
		} else {
			avatarBytes = null;
		}
		// 头像处理

		if (!"".equals(unamestr) && !"".equals(upasswdstr)) {// 如果以前登录过
			progressDialog = ProgressDialog.show(Login.this, "请稍等...",
					"正在登录...", true);

			try {
				unamestr = URLDecoder.decode(unamestr, "UTF-8");
				upasswdstr = URLDecoder.decode(upasswdstr, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			user.setUname(unamestr);
			user.setUpasswd(upasswdstr);

			needavatar = true;
//			if (avatarBytes != null) {
//				needavatar = false;
//			}
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put(Fields.NEED_AVATAR, needavatar);
			map.put(Fields.SERVER_INFO, serverinfo);
			map.put(Fields.USER, user);
			map.put(Fields.HANDLER, handler);

			txt_username.setText(unamestr, BufferType.NORMAL);
			txt_pwd.setText(upasswdstr, BufferType.NORMAL);

			new LoginTask().execute(map);
		}

	}

	class LoginListener implements OnClickListener {

		@SuppressWarnings("unchecked")
		@Override
		public void onClick(View arg0) {
			progressDialog = ProgressDialog.show(Login.this, "请稍等...",
					"正在登录...", true);
			if (txt_username.getText().toString().trim() != null
					&& !"".equals(txt_username.getText().toString().trim())
					&& txt_pwd.getText().toString().trim() != null
					&& !"".equals(txt_pwd.getText().toString().trim())) {
				user.setUname(txt_username.getText().toString().trim());
				user.setUpasswd(txt_pwd.getText().toString().trim());
			} else {
				Toast.makeText(Login.this, "请填写信息再登录!", Toast.LENGTH_SHORT)
						.show();
				handler.sendEmptyMessage(0);
				return;
			}

			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put(Fields.NEED_AVATAR, needavatar);
			map.put(Fields.SERVER_INFO, serverinfo);
			map.put(Fields.USER, user);
			map.put(Fields.HANDLER, handler);
			map.put("context", Login.this);

			new LoginTask().execute(map);

		}
	}

	/*
	 * @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
	 * 
	 * // 按下键盘上返回按钮 if (keyCode == KeyEvent.KEYCODE_BACK) {
	 * 
	 * new AlertDialog.Builder(this) .setTitle("警告") .setMessage("您确定要退出吗？")
	 * .setNegativeButton("取消", new DialogInterface.OnClickListener() {
	 * 
	 * @Override public void onClick(DialogInterface dialog, int which) { } })
	 * .setPositiveButton("确定", new DialogInterface.OnClickListener() { public
	 * void onClick(DialogInterface dialog, int whichButton) { finish(); }
	 * }).show();
	 * 
	 * return true; } else { return super.onKeyDown(keyCode, event); } }
	 */
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == Fields.NETWORK_CONNECTION_ERROR) {
				progressDialog.dismiss();
				Toast.makeText(Login.this, "网络错误！", Toast.LENGTH_SHORT).show();
			} else {
				if (userBack != null) {
					Intent intent = new Intent();
					Bundle bundle = new Bundle();
					if (!needavatar) {
						userBack.setUavatar(avatarBytes);
					}
					bundle.putSerializable(Fields.USER, userBack);
					bundle.putSerializable(Fields.SERVER_INFO, serverinfo);
					intent.putExtras(bundle);

					Editor editor = share.edit();// 取得编辑器
					editor.putString(Fields.USER_NAME, userBack.getUname());
					// 防止取到MD5密码
					editor.putString(Fields.USER_PASSWD, txt_pwd.getText()
							.toString().trim());
					// 防止取到MD5密码
					// 头像处理
					java.io.File cache = Login.this.getCacheDir();
					if (!cache.exists()) {
						cache.mkdirs();
					}
					java.io.File cacheFile = new java.io.File(cache,
							Fields.USER_AVATAR);
					if (userBack.getUavatar() != null) {
						FileUtil.wirteByteToFile(userBack.getUavatar(),
								cacheFile.getAbsolutePath());
					}
					// 头像处理
					// 离线服务器、用户信息处理
					java.io.File cacheServerinfoFile = new java.io.File(cache,
							Fields.SERVER_INFO);
					java.io.File cacheUserFile = new java.io.File(cache,
							Fields.USER);
					FileUtil.writeObjectToFile(serverinfo,
							cacheServerinfoFile.getAbsolutePath());
					FileUtil.writeObjectToFile(userBack,
							cacheUserFile.getAbsolutePath());
					// 离线服务器、用户信息处理
					// editor.putString(Fields.USER_AVATAR,
					// userBack.getUavatar());
					
					editor.putBoolean("isLogedIn", true);
					editor.commit();// 提交刷新数据

					intent.setClass(Login.this, MainTabHost.class);
					Toast.makeText(Login.this, "登录成功！", Toast.LENGTH_SHORT)
							.show();
					progressDialog.dismiss();
					startActivity(intent);

					finish();
				} else {
					progressDialog.dismiss();
					Toast.makeText(Login.this, "登录失败，请重试！", Toast.LENGTH_SHORT)
							.show();
				}
			}
		}
	};

	public static void setUserBack(UserVo userin) {
		userBack = userin;
	}

}
